import React from 'react';
import {Form, Input, Icon, Button, message} from 'antd';
import {login} from '../services/api';
import './login.css';

const FormItem = Form.Item;

class Login extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      userName:'',   //用户名
      passWord:'',   //密码
      loading:false,
    }
  }
  
// componentDidMount(){
//   message.error('登录超时或异地登录');
// }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if(!err){
        this.setState({
          userName:values.fLoginName,
          passWord:values.fPassword
        },()=>{
          this.Logins(this.state.userName.Trim(),this.state.passWord.Trim());
        })
      } 
    });
  }

  //登录
  async Logins(name,pwd){
    
      const response = await login({fLoginName:name,fPassword:pwd});
      if(response.code === 200){
        sessionStorage.setItem('accessToken', response.data);
        sessionStorage.setItem('fLoginName',name);
        sessionStorage.setItem('fPassword',pwd);
        this.props.history.push('/index');
       
      } else {
        response.msg && message.error(response.msg);
      }
  }

    render() {
      const { getFieldDecorator } = this.props.form;
      const reg =  /^\S+$/;
      return (
        <div className="login-warp">
        <div className="warp">
         <p className="word" >助友家政服务系统</p>
         <Form onSubmit={this.handleSubmit} className="login-form" >
          <FormItem>
            {getFieldDecorator('fLoginName', {
              rules: [{ required: true, message: '用户名不能为空!' },{pattern: reg, message: '不能输入空格'}],
            })(
              <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="请输入用户名"/>
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('fPassword', {
              rules: [{ required: true, message: '密码不能为空!' },{pattern: reg, message: '不能输入空格'}],
              
            })(
              <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="请输入密码" />
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('remember', {
              valuePropName: 'checked',
              initialValue: true,
            })
            // (
            //   <Checkbox>Remember me</Checkbox>
            // )
            }
            {/* <a className="login-form-forgot" href="">Forgot password</a> */}
            <Button type="primary" htmlType="submit" className="login-form-button">
             登录
            </Button>
            {/* Or <a href="">register now!</a> */}
          </FormItem>
        </Form>
          <img className="login-decorate" src={require('../assets/login2.png')}/>
        </div>
        </div>
      );
    }
}
export default Form.create()(Login);